'use strict';
const Service = require('egg').Service;
const ulid = require('../public/ulid');

class Tr069CommandService extends Service {
  async list(params) {
    try {
      const tid = params.tid;
      const where = {
        tid,
      };
      if (params.deviceType) {
        where.deviceType = params.deviceType;
      }
      if (params.typeName) {
        where.typeName = params.typeName;
      }
      const result = await this.ctx.modelmysql.Tr069Command.findAndCountAll({
        offset: parseInt((params.page - 1) * params.limit),
        limit: parseInt(params.limit),
        where,
      });
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }

  async create(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.model.Tr069Command.create({
        id: ulid.ulid(),
        tid: params.tid,
        deviceType: params.deviceType,
        typeName: params.typeName,
        keys: params.keys,
      });
      result.msg = 'create successful';
    } catch (error) {
      result.msg = 'create fail,' + error;
    }
    return result;
  }
  async delete(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.model.Tr069Command.destroy({
        where: {
          id: params.id,
        },
      });
      result.msg = 'delete successful';
    } catch (error) {
      result.msg = 'delete fail,' + error;
    }
    return result;
  }

  async update(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.model.Tr069Command.update({
        deviceType: params.deviceType,
        typeName: params.typeName,
        keys: params.keys,
      }, {
        where: {
          id: params.id,
          tid: params.tid,
        },
      });
      result.msg = 'update successful';
    } catch (error) {
      result.msg = 'update fail,' + error;
    }
    return result;
  }
}

module.exports = Tr069CommandService;
